package com.galangel.common.utils;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;


public class MinioUtility {
    //1.配置minio地址
    final static String endpoint = "http://localhost:9000";
    //2.配置minio的accessKey和secretKey（账号和密码）
    final static String accessKey = "minio";
    final static String secretKey = "minio123";

    public static String uploadingImage(String filePath) throws Exception {
        //3.将图片上传至minio
        //3.1.创建minio链接客户端
        FileInputStream fileInputStream = null;
        fileInputStream =  new FileInputStream(filePath);
        MinioClient minioClient = MinioClient.builder().credentials(accessKey, secretKey)
                .endpoint(endpoint).build();
        //3.2上传
        String fileName = new File(filePath).getName();
        // 检查文件名是否有效
        if (fileName == null || fileName.isEmpty()) {
            throw new IOException("无效的文件名");
        }
//        String objectName = fileName; // 使用原始文件名作为对象名
        // 使用uuid作为对象名

        String objectName = IdUtil.simpleUUID() + "." + FileNameUtil.getSuffix(fileName);
        objectName = "000c1ba1af5543eb8fb8b4a477ada826.webp";
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(objectName)//文件名
                .contentType("text/html/png/jpg")//文件类型
                .bucket("image")//桶名词  与minio创建的名词一致
                .stream(fileInputStream, fileInputStream.available(), -1) //文件流
                .build();
        minioClient.putObject(putObjectArgs);

        fileInputStream.close();

        //设置 Minio 存储桶（bucket）的访问策略（Policy）
        String bucketPolicy = "{"
                + "  \"Version\": \"2012-10-17\","
                + "  \"Statement\": ["
                + "    {"
                + "      \"Effect\": \"Allow\","
                + "      \"Principal\": \"*\","
                + "      \"Action\": [\"s3:GetObject\"],"
                + "      \"Resource\": [\"arn:aws:s3:::" + "image" + "/*\"]"
                + "    }"
                + "  ]"
                + "}";
        //设置为公开
        minioClient.setBucketPolicy("image",bucketPolicy);
        // 得到一个长期链接   返回给前端用于渲染
        String downloadUrl = minioClient.getObjectUrl("image", objectName);
        System.out.println("长期链接" + downloadUrl);

        // TODO 是否删除临时文件
        if (false) {
            //删除临时文件
            // 判断文件是否存在
            if(Files.exists(Paths.get(filePath))) {
                try {
                    // 删除文件
                    Files.delete(Paths.get(filePath));
                    System.out.println("临时文件删除成功");
                } catch (IOException e) {
                    // 异常处理
                    e.printStackTrace();
                }
            } else {
                System.out.println("临时文件不存在");
            }
        }
        return downloadUrl;
    }
}
